package quotation.web.personDay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import quotation.exception.BusinessException;
import quotation.web.personDay.ddd.dto.SavePersonData;
import quotation.web.personDay.ddd.entity.PersonDayEntity;
import quotation.web.personDay.ddd.form.SavePersonForm;
import quotation.web.personDay.mapper.PersonDayMapper;
import quotation.web.personDay.service.PersonDayService;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lyx
 * @date 2025/2/25
 */
@Slf4j
@Service
public class PersonDayServiceImpl extends ServiceImpl<PersonDayMapper, PersonDayEntity> implements PersonDayService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAll(SavePersonForm form) {

        List<SavePersonData> dataList = form.getDataList();

        // 对 dataList 按 from 进行排序
        dataList = dataList.stream()
                .sorted(Comparator.comparingInt(SavePersonData::getFrom))
                .collect(Collectors.toList());

        this.checkDataList(dataList);


        List<PersonDayEntity> collect = dataList.parallelStream()
                .map((data) -> BeanUtil.copyProperties(data, PersonDayEntity.class))
                .collect(Collectors.toList());
        this.saveBatch(collect);


    }

    @Override
    public List<PersonDayEntity> getAll() {
        List<PersonDayEntity> list = baseMapper.selectList();
        return list;
    }

    /*
    risk level 1:低 2:中 3:：高
     */
    @Override
    public Integer getValue(String name, Integer total, Integer riskLevel) {
        PersonDayEntity one = this.lambdaQuery()
                .eq(PersonDayEntity::getName, name)
                .ge(PersonDayEntity::getHigherLimit, total)
                .le(PersonDayEntity::getLowerLimit, total)
                .one();

        if (ObjectUtil.isNull(one)) {
            throw new BusinessException("未找到匹配的记录");
        }

        if (ObjectUtil.isNull(riskLevel)) {
            return one.getValue();
        }
        switch (riskLevel) {
            case 1:
                return one.getLow();
            case 2:
                return one.getMedium();
            case 3:
                return one.getHigh();
            default:
                throw new IllegalStateException("Unexpected value: " + riskLevel);
        }
    }

    private void checkDataList(List<SavePersonData> dataList) {
        // 无需校验单个元素或空列表
        if (dataList.size() < 2) {
            return;
        }

        for (int i = 0; i < dataList.size() - 1; i++) {
            SavePersonData current = dataList.get(i);
            SavePersonData next = dataList.get(i + 1);

            if (current.getTo() + 1 != next.getFrom()) {
                throw new IllegalArgumentException(
                        String.format("数据区间不连续：当前元素 to=%d，下一元素 from=%d", current.getTo(), next.getFrom())
                );
            }

            if (current.getValue() != null && next.getValue() != null) {
                ensureNonDecreasing(current.getValue(), next.getValue(), "value");
            } else {
                ensureNonDecreasing(current.getHigh(), next.getHigh(), "high");
                ensureNonDecreasing(current.getMedium(), next.getMedium(), "medium");
                ensureNonDecreasing(current.getLow(), next.getLow(), "low");
            }
        }
    }

    private void ensureNonDecreasing(Integer currentVal, Integer nextVal, String fieldName) {
        if (currentVal != null && nextVal != null && currentVal > nextVal) {
            throw new IllegalArgumentException(fieldName + " 数据无序");
        }
    }
}
